package com.valuedaas.schoolsafety.common.filter;

import com.valuedaas.schoolsafety.common.Constants;
import com.valuedaas.schoolsafety.common.base.Result;
import com.valuedaas.schoolsafety.controller.user.vo.User;
import com.valuedaas.schoolsafety.service.user.UserService;
import com.valuedaas.schoolsafety.util.SecurityUtil;
import com.valuedaas.schoolsafety.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import javax.annotation.Priority;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * session 拦截校验器
 * 
 * @author chenhua
 *
 */
@Component
@WebFilter(filterName = "cookieFilter", urlPatterns = "*.do")
@Priority(0)
public class CookieFilter extends OncePerRequestFilter {

	static final Logger LOG = LoggerFactory.getLogger(CookieFilter.class);
    @Autowired
    private UserService userService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        User sessionUser = this.getSessionUser(httpRequest);
        if (sessionUser == null
        ){
            // 尝试从cookie中，恢复session信息
            rememberMe(httpRequest, httpResponse);
        }
        chain.doFilter(httpRequest, httpResponse);
        return;
	}


    private String[] decodeUserAccountAndPasswordByCookieToken(HttpServletRequest req) {
        Cookie rememberCookie = WebUtils.getCookie(req, Constants.REMEMBERME_COOKIE);
        if (rememberCookie == null || StringUtils.isEmpty(rememberCookie.getValue())) {
            return null;
        }
        String[] userArr = SecurityUtil.decodeRememberToken(rememberCookie.getValue());
        if (null==userArr || userArr.length != 3) {
            return null;
        }
        return userArr;

    }

    private User getSessionUser(HttpServletRequest httpReq) {
        Object obj = httpReq.getSession().getAttribute(Constants.SESSION_KEY);
        if (obj == null) {
            return null;
        }
        if (obj instanceof User) {
            return (User) obj;
        }
        return null;
    }

    private void rememberMe(HttpServletRequest req, HttpServletResponse res) {
        String[] userArr = decodeUserAccountAndPasswordByCookieToken(req);
        if (userArr == null) {
            return;
        }
        String account = userArr[0];
        String pwdMd5 = userArr[1];
        User user = userService.loginWithMd5Pwd(account, pwdMd5);
        if (user == null) {
            return;
        } else {
            RequestContextHolder.getRequestAttributes().setAttribute(Constants.SESSION_KEY, user,
                    RequestAttributes.SCOPE_SESSION);
        }
    }
}